package boc.sx.gateway.socket.client.initializer;

import boc.sx.gateway.protocal.DefaultCodec;
import boc.sx.gateway.socket.client.handler.SimpleClientHandler;
import boc.sx.gateway.socket.client.support.ChannelInitializerBuilder;
import boc.sx.gateway.socket.client.support.Protocol;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/*
 * @author zmx
 * @date 2022/8/18 10:04
 */
@Component
@Scope("prototype")
@Protocol("simple")
public class SimpleClientInitializer extends ChannelInitializer<SocketChannel> implements ChannelInitializerBuilder {

    public String requestPath;

    public Object msg;

    public String requestCode;

    public String acceptDataType;   //期望的数据格式

    public String sourceDataType;   //接受到的数据

    public SimpleClientInitializer() {
    }

    public SimpleClientInitializer(String requestCode, Object msg,String requestPath) {
        this.requestPath = requestPath;
        this.msg = msg;
        this.requestCode = requestCode;
    }

    @Override
    public ChannelInitializer config(String requestCode, Object msg,String requestPath){

        SimpleClientInitializer initializer = new SimpleClientInitializer(requestCode,msg,requestPath);
        return initializer;
    }

    /**
     * 初始化channel
     */
    @Override
    protected void initChannel(SocketChannel channel) {
        SimpleClientHandler nettyClientHandler = new SimpleClientHandler(requestPath,requestCode,msg);
        channel.pipeline()
                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,3,4,0,0))
                .addLast(new DefaultCodec())
                .addLast(new StringDecoder(Charset.defaultCharset()))
                .addLast(nettyClientHandler);
    }
}
